package com.shanjupay.merchant.controller;

import com.shanjupay.common.domain.BusinessException;
import com.shanjupay.common.domain.CommonErrorCode;
import com.shanjupay.common.util.PhoneUtil;
import com.shanjupay.merchant.api.MerchantService;
import com.shanjupay.merchant.api.dto.MerchantDTO;
import com.shanjupay.merchant.common.util.SecurityUtil;
import com.shanjupay.merchant.convert.MerchantDetailConvert;
import com.shanjupay.merchant.convert.MerchantRegisterConvert;
import com.shanjupay.merchant.service.FileService;
import com.shanjupay.merchant.service.SmsService;
import com.shanjupay.merchant.vo.MerchantDetailVO;
import com.shanjupay.merchant.vo.MerchantRegisterVO;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.IOException;
import java.util.UUID;

/**
 * @author whb
 * @create 2021-11-15 20:57
 * @decription 商户服务控制类
 */
@Slf4j
@Api(value = "商户平台-商户相关1", tags = "商户平台-商户相关2", description = "商户平台-商户相关3")
@RestController
public class MerchantController {
    @Reference
    private MerchantService merchantService;
    @Autowired
    private ConfigurableApplicationContext applicationContext;
    @Autowired
    private SmsService smsService;
    @Autowired
    private FileService fileService;

    @ApiOperation("根据id查询商户")
    @GetMapping(value = "/merchants/{id}")
    public MerchantDTO queryMerchantById(@PathVariable("id") Long id) {
        MerchantDTO merchantDTO = merchantService.queryMerchantById(id);
        return merchantDTO;
    }

    @ApiOperation("获取登录用户的商户信息")
    @RequestMapping(value = "/my/merchants",method = RequestMethod.GET)
    public MerchantDTO getLoginMerchantInfo(){
        Long merchantId = SecurityUtil.getMerchantId();
        return merchantService.queryMerchantById(merchantId);
    }

    @ApiOperation("查询Nacos中的路径配置")
    @GetMapping(value = "/config")
    public String getConfig() {
        return applicationContext.getEnvironment().getProperty("server.servlet.context-path");
    }

    //忽略接口，不让其在Swagger文档中显示
    @ApiIgnore
    /*@ApiOperation("测试hi")
    @ApiImplicitParam(name="name",value = "姓名",required = true,dataType = "String")*/
    @PostMapping(value = "/hi")
    public String hi(String name) {
        return "hi" + name;
    }

    /**
     * 获取手机验证码对应的key
     *
     * @param phone
     * @return
     */
    @ApiOperation("获取手机验证码")
    @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query")
    @RequestMapping(value = "/sms", method = RequestMethod.GET)
    public String getSMSCode(@RequestParam("phone") String phone) {
        log.info("向手机号：{}发送验证码", phone);
        return smsService.getSmsKey(phone);
    }

    /**
     * 商户注册
     *
     * @param merchantRegisterVO
     * @return
     */
    @ApiOperation("商户注册")
    @ApiImplicitParam(value = "商户注册信息", name = "merchantRegisterVO", required = true, dataType = "MerchantRegisterVO", paramType = "body")
    @RequestMapping(value = "/merchants/register", method = RequestMethod.POST)
    public MerchantRegisterVO registerMerchant(@RequestBody MerchantRegisterVO merchantRegisterVO) {

        //传入对象非空校验
        if (merchantRegisterVO == null) {
            throw new BusinessException(CommonErrorCode.E_100108);
        }

        //手机号非空校验
        if (StringUtils.isBlank(merchantRegisterVO.getMobile())) {
            throw new BusinessException(CommonErrorCode.E_100112);
        }

        //手机号格式合法性校验
        if (!PhoneUtil.isMatches(merchantRegisterVO.getMobile())) {
            throw new BusinessException(CommonErrorCode.E_100109);
        }

        //密码非空校验
        if (StringUtils.isBlank(merchantRegisterVO.getPassword())) {
            throw new BusinessException(CommonErrorCode.E_100111);
        }

        //手机验证码和key非空校验
        if (StringUtils.isBlank(merchantRegisterVO.getVerifiyCode()) || StringUtils.isBlank(merchantRegisterVO.getVerifiykey())) {
            throw new BusinessException(CommonErrorCode.E_100103);
        }

        //int i=1/0;//制造不可预测的错误，检验系统全局异常处理类

        //校验短信验证码
        smsService.checkVerifiyCode(merchantRegisterVO.getVerifiykey(), merchantRegisterVO.getVerifiyCode());
        //注册商户
        /*MerchantDTO merchantDTO = new MerchantDTO();
        merchantDTO.setUsername(merchantRegisterVO.getUsername());//商户用户名
        merchantDTO.setMobile(merchantRegisterVO.getMobile());//商户手机号
        merchantDTO.setPassword(merchantRegisterVO.getPassword());//商户密码*/

        //通过MapStruct工程将vo数据类型转成dto数据类型，简化转化过程
        MerchantDTO merchantDTO = MerchantRegisterConvert.INSTANCT.vo2dto(merchantRegisterVO);

        merchantService.addMerchant(merchantDTO);//调用商户服务的Dubbo接口，保存商户信息

        return merchantRegisterVO;
    }

    /**
     * 上传证件照
     *
     * @param multipartFile
     * @return
     */
    @ApiOperation("上传证件照")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(@ApiParam(value = "证件照", required = true) @RequestParam("file") MultipartFile multipartFile) throws IOException {
        //文件原始名称
        String originalFilename = multipartFile.getOriginalFilename();
        //文件的扩展名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //自定义文件名（上传到七牛云的文件名）
        String fileName = UUID.randomUUID() + suffix;
        return fileService.upload(multipartFile.getBytes(), fileName);
    }

    /**
     * 商户资质申请
     * @param merchantInfo 资质申请信息
     */
    @ApiOperation("资质申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "merchantInfo",value = "商户资质认证信息",required = true,dataType = "MerchantDetailVO",paramType = "body")
    })
    @RequestMapping(value = "/my/merchants/save",method = RequestMethod.POST)
    public void saveMerchant(@RequestBody MerchantDetailVO merchantInfo){
        //解析Token，获取当前登录商户的id
        long merchantId= SecurityUtil.getMerchantId();

        MerchantDTO merchantDTO = MerchantDetailConvert.INSTANCT.vo2dto(merchantInfo);
        //调用商户dubbo服务，保存资质申请信息
        merchantService.applyMerchantv(merchantId, merchantDTO);
    }
}
